#include "udpServer.hpp"
#include <iostream>
#include <memory>
#include <unordered_map>
#include <fstream>
#include <signal.h>

using namespace server;


static void Usage(const std::string &proc)
{
    std::cout << "\nUsage:\n\t" << proc << " local_port" << std::endl
              << std::endl;
}

// 业务逻辑一-翻译单词
void handleMessage(int sockfd, std::string &clientIP, uint16_t clientPort, std::string &msg)
{
    std::string response_msg = msg; // 响应数据 -- 对客户端的消息做出响应

    response_msg += " [server echo]";

    // 发送响应消息给客户端
    struct sockaddr_in client;
    bzero(&client, sizeof(client));

    client.sin_family = AF_INET;
    client.sin_port = htons(clientPort);
    client.sin_addr.s_addr = inet_addr(clientIP.c_str());

    sendto(sockfd, response_msg.c_str(), response_msg.size(), 0, (struct sockaddr *)&client, sizeof(client));
}

/*udpServer的运行
格式：./udpServer port
*/
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(USAGE_ERROR);
    }

    // 1. 创建服务器
    uint16_t port = atoi(argv[1]);

    std::unique_ptr<udpServer> usvr(new udpServer(handleMessage, port));

    // 2. 初始化服务器
    usvr->initServer();
    // 3. 启动服务器
    usvr->start();

    return 0;
}
